package org.jcubic.mvc.servlet;


import org.jcubic.mvc.mapping.RequestMapping;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class ControllerServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();

        if (AppMVCContext.getRequestMappingManager().getStringRequestMappingMap().containsKey(uri)) {
            Class clazz = null;
            RequestMapping requestMapping = AppMVCContext.getRequestMappingManager().getStringRequestMappingMap().get(uri);
            String classFullName = requestMapping.getClassFullName();
            try {
                clazz = Thread.currentThread().getContextClassLoader().loadClass(requestMapping.getClassName());
            } catch (ClassNotFoundException e) {
                System.out.println("创建实例 [" + requestMapping.getClassName() + "] 失败");
                e.printStackTrace();
            }
            if (clazz == null) {
                try {
                    clazz = Class.forName(requestMapping.getClassName());
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
            try {
                Object o = clazz.newInstance();
                //TODO 处理访问URL
//                clazz.method
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            System.out.println("请求URI：" + uri);
        } else {
            System.out.println("未添加Request" + uri);
        }
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }
}
